var express = require('express')
var md5 = require('./utils/md5')
var idGenerator = require('./utils/idGenerator')
var router = express.Router()
var user = require('./model/user')
var comment = require('./model/comment')

function filter(req, res) {
    if (!req.session.userSession) {
        return res.send('当前未登陆!请先<a href="/login">登陆</a>')
    }
}

function returnErr(next, err) {
    if (err) {
        console.log(err);
        return next(err)
    }
}
router.get('/', function(req, res, next) {
    var userSession = req.session.userSession
    comment.find(function(err, data) {
        returnErr(next, err)
        res.render('index.html', {
            userSession: userSession,
            comments: data,
            flag: true
        })
    })

})
router.get('/getComments', function(req, res, next) {
    comment.find(function(err, data) {
        returnErr(next, err)
        res.json(data)
    })
})
router.get('/register', function(req, res, next) {
    res.render('register.html')
})
router.post('/register', function(req, res, next) {
    user.findOne({
        $or: [{
                'email': req.body.email
            },
            {
                'nickname': req.body.nickname
            }
        ]
    }, function(err, data) {
        returnErr(next, err)
        if (data) {
            return res.status(200).json({
                err_code: 1,
                message: 'Eamil or nickname already exists'
            })
        }
        //使用md5二次加密密码
        req.body.password = md5(req.body.password + 'wwy')
        new user(req.body).save(function(err) {
            if (err) {
                return res.status(500).json({
                    err_code: 500,
                    message: 'Server err'
                })
            }
            return res.status(200).json({
                    err_code: 0,
                    message: 'registerSuccess'
                })
                //服务端重定向只对同步请求有效，异步请求无效
                //当客户端页面发起异步请求 只能通过客户端页面进行重定向
        })
    })
})
router.get('/login', function(req, res, next) {
    res.render('login.html')
})
router.post('/login', function(req, res, next) {
    req.body.password = md5(req.body.password + 'wwy')
    user.findOne(req.body, function(err, data) {
        returnErr(next, err)
        if (!data) {
            return res.status(200).json({
                err_code: 1,
                message: 'email or password is invalid'
            })
        }
        req.session.userSession = data
        res.status(200).json({
            err_code: 0,
            message: 'loginSuccess'
        })
    })
})
router.get('/logout', function(req, res, next) {
    if (req.session.userSession) {
        req.session.userSession = null
        res.redirect('/')
    }
})
router.get('/profile', function(req, res, next) {
    filter(req, res)
    comment.find({
        'author.authorId': req.session.userSession._id
    }, function(err, comments) {
        returnErr(next, err)
        user.find({
            'fans': req.session.userSession._id
        }, function(err, focus) {
            returnErr(next, err)
            user.find({
                'focus': req.session.userSession._id
            }, function(err, fans) {
                returnErr(next, err)
                res.render('settings/profile.html', {
                    userSession: req.session.userSession,
                    comments: comments,
                    focus: focus,
                    fans: fans
                })
            })

        })

    })

})
router.post('/profile', function(req, res, next) {
    var information = req.body
    req.body.lastModifiedTime = new Date()
    user.findByIdAndUpdate(information.id, information, function(err, data) {
        returnErr(next, err)
        user.findById(information.id, function(err, data) {
            req.session.userSession = data
            res.status('200').json({
                err_code: 0,
                message: 'updateSuccess'
            })
        })
    })
})
router.get('/admin', function(req, res, next) {
    filter(req, res)
    res.render('settings/admin.html', {
        user: req.session.userSession
    })
})
router.post('/admin', function(req, res, next) {
    var passwordList = req.body
    user.findById(req.session.userSession._id, function(err, data) {
        returnErr(next, err)
        if (md5(passwordList.password + 'wwy') != data.password) {
            return res.status(200).json({
                err_code: 1,
                message: 'old password is not invalid'
            })
        }
        if (passwordList.newpassword != passwordList.newpassword1) {
            return res.status(200).json({
                err_code: 2,
                message: 'new password is not invalid'
            })
        }
        user.findByIdAndUpdate(data._id, {
            password: md5(passwordList.newpassword + 'wwy')
        }, function(err, data) {
            returnErr(next, err)
            req.session.userSession = null
            res.status(200).json({
                err_code: 0,
                message: '修改成功'
            })
        })
    })
})
router.post('/deleteUser', function(req, res, next) {
    user.findByIdAndDelete(req.session.userSession._id, function(err, ret) {
        returnErr(next, err)
        res.status(200).json({
            err_code: 0,
            message: 'delete success'
        })

    })
})
router.get('/publish', function(req, res, next) {
    filter(req, res)
    res.render('topic/publish.html', {
        userSession: req.session.userSession,
        flag: false
    })
})
router.post('/publish', function(req, res, next) {
    var commentInfo = req.body
    commentInfo.author = {
        authorId: req.session.userSession._id,
        authorName: req.session.userSession.nickname
    }
    new comment(commentInfo).save(function(err, ret) {
        returnErr(next, err)
        user.findByIdAndUpdate(req.session.userSession._id, {
            $push: {
                'comments': ret._id
            }
        }, function(err) {
            returnErr(next, err)
            res.status(200).json({
                err_code: 0,
                message: 'publishSuccess'
            })
        })
    })
})
router.get('/viewUser', function(req, res, next) {

    user.findById(req.query.user_id, function(err, data) {
        returnErr(next, err)
        res.render('toViewUser.html', {
            user: data,
            userSession: req.session.userSession,
        })
    })
})
router.get('/viewComment', function(req, res, next) {
    var comment_id = req.query.comment_id
    comment.findById(comment_id, function(err, data) {
        returnErr(next, err)
        if (req.session.userSession) {
            comment.findByIdAndUpdate(comment_id, {
                $addToSet: {
                    'read': req.session.userSession._id
                }
            }, function(err) {
                returnErr(next, err)
                user.findByIdAndUpdate(req.session.userSession._id, {
                    $addToSet: {
                        'readed': comment_id
                    }
                }, function(err) {
                    returnErr(next, err)
                    res.render('toViewComment.html', {
                        comment: data,
                        userSession: req.session.userSession
                    })
                })
            })
        } else {
            res.render('toViewComment.html', {
                comment: data,
                userSession: req.session.userSession
            })
        }
    })
})
router.post('/focusOn', function(req, res, next) {
    var commentUserId = req.body.commentUserId
    var userSessionId = req.session.userSession._id
    if (userSessionId === commentUserId) {
        return res.json({
            err_code: 1,
            message: 'do not focus yourselef'
        })
    }
    user.findByIdAndUpdate(userSessionId, {
        $addToSet: {
            'focus': commentUserId
        }
    }, function(err, my) {
        returnErr(next, err)
        user.findByIdAndUpdate(commentUserId, {
            $addToSet: {
                'fans': userSessionId
            }
        }, function(err, data) {
            returnErr(next, err)
            req.session.userSession = my
            res.status(200).json({
                err_code: 0,
                message: 'focus success'
            })
        })
    })

})
router.get('/focusOff', function(req, res, next) {
    var focusId = req.query.user_id
    user.findByIdAndUpdate(req.session.userSession._id, {
        $pull: {
            'focus': focusId
        }
    }, function(err, data) {
        returnErr(next, err)
        user.findByIdAndUpdate(focusId, {
            $pull: {
                'fans': req.session.userSession._id
            }
        }, function(err, data) {
            returnErr(next, err)
            res.redirect('/profile')
        })

    })
})
router.post('/doNice', function(req, res, next) {
    var commentId = req.body.commentId
    var userSessionId = req.session.userSession._id
    comment.findByIdAndUpdate(commentId, {
        $addToSet: {
            'like': req.session.userSession._id
        }
    }, function(err, data) {
        returnErr(next, err)
        user.findByIdAndUpdate(userSessionId, {
            $addToSet: {
                'liked': commentId
            }
        }, function(err) {
            returnErr(next, err)
            res.status(200).json({
                err_code: 0,
                message: 'doNice success'
            })
        })

    })

})
router.post('/doReply', function(req, res, next) {
    var replyId = idGenerator()
    var replyContent = req.body
    comment.findByIdAndUpdate(replyContent.commentId, {
        $addToSet: {
            'replys': {
                "id": replyId,
                "userId": req.session.userSession._id,
                "userName": req.session.userSession.nickname,
                "message": replyContent.replyMsg,
                "replyTime": new Date()
            }
        }
    }, function(err, data) {
        returnErr(next, err)
        user.findByIdAndUpdate(req.session.userSession._id, {
            $addToSet: {
                'replyed': {
                    "id": replyId,
                    "commentId": replyContent.commentId,
                    "author": data.author.authorName,
                    "message": replyContent.replyMsg,
                    "replyTime": new Date()
                }
            }
        }, function(err, data) {
            req.session.userSession = data
            returnErr(next, err)
            res.status(200).json({
                err_code: 0,
                message: 'reply success'
            })
        })
    })
})
router.get('/deleteComment', function(req, res, next) {
    var commentId = req.query.comment_id
    comment.findByIdAndRemove(commentId, function(err) {
        returnErr(next, err)
        res.redirect('/profile')
    })
})
router.get('/deleteReplyed', function(req, res, next) {
    var commentId = req.query.commentId
    var replyId = req.query.replyId
    var replyUserId = req.query.replyUserId
    comment.update({
        '_id': commentId,
        'replys.userId': replyUserId,
        'replys.id': replyId
    }, {
        $pull: {
            'replys': { 'userId': replyUserId, 'id': replyId }
        }
    }, function(err, data) {
        returnErr(next, err)
        user.update({
            '_id': replyUserId,
            'replyed.commentId': commentId,
            'replyed.id': replyId
        }, {
            $pull: {
                'replyed': {
                    'id': replyId,
                    'commentId': commentId
                }
            }
        }, function(err, data) {
            console.log('err:' + err)
            console.log('data:' + data)
            res.redirect('/viewComment?comment_id=' + commentId)
        })

    })
})
router.get('/forgot', function(req, res, next) {
    res.render('forgotPassword.html')
})
router.post('/validation', function(req, res, next) {
    var email = req.body
    user.findOne(email, function(err, data) {
        returnErr(next, err)
        if (!data) {
            return res.status(200).json({
                err_code: 1,
                message: 'email is invalid'
            })
        }
        req.session.forgot = data
        res.status(200).json({
            err_code: 0,
            message: 'email is valid'
        })
    })

})
router.get('/validation', function(req, res, next) {
    if (!req.session.forgot) {
        returnErr(next, {
            message: '请先输入邮箱'
        })
    }
    res.render('updatePassword.html')
})
router.post('/forgot', function(req, res, next) {
    var passwordList = req.body
    if (passwordList.newPassword != passwordList.newPassword1) {
        return res.status(200).json({
            err_code: 1
        })
    }
    user.findByIdAndUpdate(req.session.forgot._id, {
        password: md5(passwordList.newPassword1 + 'wwy')
    }, function(err, data) {
        returnErr(next, err)
        req.session.forgot = null
        res.status(200).json({
            err_code: 0
        })
    })

})
module.exports = router